#include "kraw.h"
#include "d3d9/d3d9display.h"

#ifdef _WIN32

using namespace Kraw;

/// window message handler function
LRESULT WINAPI WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
    //get the display* from the user data
    D3D9Display* display = (D3D9Display*) GetWindowLong( hWnd, GWL_USERDATA );
    Input* input = Input::Get();
    
    switch (msg)
    {
        case WM_DESTROY:
            display->OnWindowDestroy();
            PostQuitMessage( 0 );
            return 0;

        case WM_PAINT:
            //Render();
            ValidateRect( hWnd, NULL );
            return 0;

        //handle input from mouse
        case WM_MOUSEMOVE:
            {
                short x = LOWORD(lParam);
                short y = HIWORD(lParam);
                input->mouse_x = x;
                input->mouse_y = y;
                input->relmouse_x = x / display->width;
                input->relmouse_y = y / display->height;
            }
            break;
    }

    return DefWindowProc( hWnd, msg, wParam, lParam );
}

bool D3D9Display::OpenWindow()
{
	//class may be already registered by another device
	if (numDisplays == 0)
	{
		WNDCLASSEX wc =
		{
			sizeof( WNDCLASSEX ), CS_CLASSDC, WndProc, 0L, 0L,
			GetModuleHandle( NULL ), NULL, NULL, NULL, NULL,
			"Kraw::D3D9Display", NULL
		};
		RegisterClassEx( &wc );
	}

	++numDisplays;

    D3D9Display* self = (D3D9Display*) this;

    // select left, top, width, height of this display
    self->hWnd = CreateWindow( "Kraw::D3D9Display", "Kraw::D3D9Display Display",
                               WS_OVERLAPPEDWINDOW, left, top, width, height,
                               NULL, NULL, GetModuleHandle( NULL ), NULL );

    SetWindowLong( self->hWnd, GWL_USERDATA, (LONG) this );
    
    return true;
}

void D3D9Display::CloseWindow()
{
    --numDisplays;
    if (numDisplays == 0)
    {
        UnregisterClass( "Kraw::D3D9Display", GetModuleHandle( NULL ) );
    }
}

void D3D9Display::OnWindowDestroy()
{
    //close the display before the window is destroyed
    this->bIsQuitRequested = true;
}

#endif _WIN32
